package com.hltx.controller.pay;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;
import com.hltx.constants.PayConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.pay.PayInfo;
import com.hltx.pojo.pay.PayInfoAlipay;
import com.hltx.resolver.DefiniteException;
import com.hltx.service.brokerage.impl.ConsumeBrokerageV2Service;
import com.hltx.service.pay.AlipayPayManager;
import com.hltx.service.pay.PayManager;
import com.hltx.util.CommonUtil;
import com.hltx.util.RequestHandler;
import com.hltx.util.ResultInfo;







/**
 * 支付回调controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping("/notify")
public class PayNotifyController extends BaseController{

	protected Logger logger = LoggerFactory.getLogger(PayNotifyController.class);
	
	@Value("${wx.apikey}")
	private String key;
	
	@Autowired
	private PayManager payService;
	
	@Autowired
	private AlipayPayManager alipayPayService;
	
	@Autowired
	private ConsumeBrokerageV2Service brokerageV2Service;
	
	@RequestMapping(value="/wxNotify")
	public void wxNotify(HttpServletRequest request,
			HttpServletResponse response){
		this.logBefore(logger, "微信支付回调-开始");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
		//读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
        while ((s = in.readLine()) != null){  
            sb.append(s);  
        }  
        in.close();  
        inputStream.close();  
		
        Map<String, String> resMap = CommonUtil.xmlBody2map(sb.toString(), "xml");
        String resXml = "";
        if(resMap == null || resMap.isEmpty()){
        	resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
        }else{
        	if(PayConstant.CODE_SUC.equals(resMap.get("return_code"))){
        		String sign = resMap.get("sign");
        		RequestHandler reqH = new RequestHandler();
        		reqH.setKey(key);
        		String mySign = reqH.createSign(resMap);
        		if(StringUtils.isNotEmpty(mySign) && StringUtils.equals(mySign, sign)){
        			
        			ResultInfo resInfo = payService.updateWxOrder(resMap ,sb.toString());
        			resultMap.put("result", resInfo);
        			if(StringUtils.equals(resInfo.getState(), ResultInfo.SUCCESS)){
        				PayInfo pi = (PayInfo) resInfo.getObj();
        				if(pi.getTotalPointsNum() <= 0){
        					brokerageV2Service.bounsShunt(pi.getId());
        				}
        				
        			}
        			resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        		}else{
        			resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[参数错误]]></return_msg></xml>";
        		}
        		
        	}else{
        		resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
        	}
        }
        //------------------------------  
        //处理业务完毕  
        //------------------------------  
        BufferedOutputStream out = new BufferedOutputStream(  
                response.getOutputStream());  
        out.write(resXml.getBytes());  
        out.flush();  
        out.close();  
        
		}catch(Exception e){
			e.printStackTrace();
			
		}
		
		
	}
	
	@RequestMapping(value="/lineWeChatNotify")
	public void lineWeChatNotify(HttpServletRequest request,
			HttpServletResponse response){
		this.logBefore(logger, "线下微信支付回调-开始");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
		//读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
        while ((s = in.readLine()) != null){  
            sb.append(s);  
        }  
        in.close();  
        inputStream.close();  
		
        Map<String, String> resMap = CommonUtil.xmlBody2map(sb.toString(), "xml");
        String resXml = "";
        if(resMap == null || resMap.isEmpty()){
        	resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
        }else{
        	if(PayConstant.CODE_SUC.equals(resMap.get("return_code"))){
        		String sign = resMap.get("sign");
        		RequestHandler reqH = new RequestHandler();
        		reqH.setKey(key);
        		String mySign = reqH.createSign(resMap);
        		if(StringUtils.isNotEmpty(mySign) && StringUtils.equals(mySign, sign)){
        			
        			ResultInfo resInfo = payService.updateLineWxPay(resMap ,sb.toString());
        			resultMap.put("result", resInfo);
        			if(StringUtils.equals(resInfo.getState(), ResultInfo.SUCCESS)){
        				PayInfo pi = (PayInfo) resInfo.getObj();
        				if(pi.getTotalPointsNum() <= 0){
        					brokerageV2Service.offlineBounsShunt(pi);
        				}
        				
        			}
        			resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        		}else{
        			resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[参数错误]]></return_msg></xml>";
        		}
        		
        	}else{
        		resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
        	}
        }
        //------------------------------  
        //处理业务完毕  
        //------------------------------  
        BufferedOutputStream out = new BufferedOutputStream(  
                response.getOutputStream());  
        out.write(resXml.getBytes());  
        out.flush();  
        out.close();  
        
		}catch(Exception e){
			e.printStackTrace();
			
		}
		
		
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/aliPayNotify")
	public void aliPayNotify(HttpServletRequest request,
			HttpServletResponse response){
		this.logBefore(logger, "支付宝支付回调-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, String> map = new HashMap<String, String>();
		try {
			Map<String, String[]> params = request.getParameterMap();
			for (Entry<String, String[]> entry : params.entrySet()) {
				if (entry.getValue() != null && entry.getValue().length == 1) {
					map.put(entry.getKey(), entry.getValue()[0]);
				}
			}
			PayInfoAlipay result = alipayPayService.getNotifyResult(map);
			ResultInfo resInfo = payService.updateAlipayOrder(result);
			resMap.put("result", resInfo);
			if(StringUtils.equals(resInfo.getState(), ResultInfo.SUCCESS)){
				PayInfo pi = (PayInfo) resInfo.getObj();
				if(pi.getTotalPointsNum() <= 0){
					brokerageV2Service.bounsShunt(pi.getId());
				}
				
			}
			System.out.println(result.getOutTradeNo());
		} catch (AlipayApiException e) {
			throw new DefiniteException(e.getMessage());
		}
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/lineAliPayNotify")
	public void lineAliPayNotify(HttpServletRequest request,
			HttpServletResponse response){
		this.logBefore(logger, "线下支付宝支付回调-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, String> map = new HashMap<String, String>();
		try {
			Map<String, String[]> params = request.getParameterMap();
			for (Entry<String, String[]> entry : params.entrySet()) {
				if (entry.getValue() != null && entry.getValue().length == 1) {
					map.put(entry.getKey(), entry.getValue()[0]);
				}
			}
			PayInfoAlipay result = alipayPayService.getNotifyResult(map);
			ResultInfo resInfo = payService.updateLineAlipayOrder(result);
			resMap.put("result", resInfo);
			if(StringUtils.equals(resInfo.getState(), ResultInfo.SUCCESS)){
				PayInfo pi = (PayInfo) resInfo.getObj();
				if(pi.getTotalPointsNum() <= 0){
					brokerageV2Service.offlineBounsShunt(pi);
				}
				
			}
			System.out.println(result.getOutTradeNo());
		} catch (AlipayApiException e) {
			throw new DefiniteException(e.getMessage());
		}
	}
	
	
}
